package io.github.lingalone.monsterauth.auth;

import com.fasterxml.jackson.databind.ObjectMapper;

import io.github.lingalone.monsterauth.controller.ReturnMsg;
import io.github.lingalone.monsterauth.util.CookieUtil;
import io.github.lingalone.monsterauth.util.HeaderUtil;
import io.github.lingalone.monsterauth.util.JwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import java.io.PrintWriter;

/**
 * Created with IntelliJ IDEA.
 *
 * @author <a href="https://github.com/lingalone">lingalone</a>
 * @version 1.0.0
 * @link
 * @since 2018/7/24
 */

@Configuration
@EnableWebSecurity
@EnableConfigurationProperties({AuthProperties.class})
class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    JwtUtil jwtUtil;
    @Autowired
    private AuthProperties authProperties;


    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.csrf().disable()

                .authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/error").permitAll()
                .antMatchers("/login").permitAll()
                .antMatchers("/actuator/**").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/login")
                .successHandler((request, response, authentication) -> {
                    Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
                    if (principal != null && principal instanceof UserDetails) {
                        UserDetails user = (UserDetails) principal;
                        System.out.println("loginUser:"+user.getUsername());
                        String token = jwtUtil.generateToken(authProperties.getJwtKey(), user.getUsername());
                        HeaderUtil.create(response,token);
                        CookieUtil.create(response, authProperties.getJwtCookieName(), token, false, -1, authProperties.getServiceDomain());
                        if(StringUtils.isNoneBlank(request.getParameter("redirect"))){
                            if (StringUtils.isNotBlank(request.getParameter("type"))
                                    && "api".equalsIgnoreCase(request.getParameter("type"))){

                                response.setStatus(HttpStatus.OK.value());
                                response.setCharacterEncoding("UTF-8");
                                response.setContentType("application/json");
                                ReturnMsg<String> returnMsg = new ReturnMsg<>();
                                returnMsg.setRequestStatus(HttpStatus.OK.value(),"登录成功",null);
                                returnMsg.setToken(token);
                                PrintWriter pw = response.getWriter();
                                pw.write(new ObjectMapper().writeValueAsString(returnMsg));
                            }else{
                                response.sendRedirect(request.getParameter("redirect"));
                            }
                        }else{
                            response.setStatus(HttpStatus.OK.value());
                            response.setCharacterEncoding("UTF-8");
                            response.setContentType("application/json");
                            ReturnMsg<String> returnMsg = new ReturnMsg<>();
                            returnMsg.setRequestStatus(HttpStatus.OK.value(),"登录成功",null);
                            PrintWriter pw = response.getWriter();
                            pw.write(new ObjectMapper().writeValueAsString(returnMsg));
                        }

                    }
                })
                .failureHandler((request, response, authenticationException) -> {
//                    if(StringUtils.isNoneBlank(request.getParameter("redirect"))){
//                        response.sendRedirect("/error1");
//                    }else{
                        response.setStatus(HttpStatus.UNAUTHORIZED.value());
                        response.setCharacterEncoding("UTF-8");
                        response.setContentType("application/json");
                        ReturnMsg<String> returnMsg = new ReturnMsg<>();
                        returnMsg.setRequestStatus(HttpStatus.UNAUTHORIZED.value(),"验证非法", authenticationException.getMessage());
                        PrintWriter pw = response.getWriter();
                        pw.write(new ObjectMapper().writeValueAsString(returnMsg));
//                    }

                })
                .and()
                .logout()
                .logoutUrl("/logout")
                .deleteCookies(authProperties.getJwtCookieName())
                .logoutSuccessUrl("/login");


    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(authProvider());
    }

    @Autowired
    private AuthUserDetailService authUserDetailService;


    @Bean
    public AuthProvider authProvider(){
        AuthProvider authProvider = new AuthProvider();
        authProvider.setPasswordEncoder(passwordEncoder());
        authProvider.setUserDetailsService(authUserDetailService);
        return authProvider;
    }

    @Bean
    public static PasswordEncoder passwordEncoder() {
//        return NoOpPasswordEncoder.getInstance();
        return new BCryptPasswordEncoder();
    }
}